package com.ocom.srvpamh.business.impl;


import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.ocom.common.entity.company.EntityCompanyConfig;
import com.ocom.common.entity.company.EntityCompanyInfo;
import com.ocom.common.entity.payconfig.EntityVoucherData;
import com.ocom.common.request.human.UpdateUserRegionRequest;
import com.ocom.common.request.simple.SmsRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.CommonUtil;
import com.ocom.common.utils.DateUtils;
import com.ocom.common.utils.StringUtils;
import com.ocom.common.vo.accessdevice.RegionAreaInfo;
import com.ocom.common.vo.recode.DoorRecodeVo;
import com.ocom.redis.util.RedisUtil;
import com.ocom.srvpamh.business.YkmHandleService;
import com.ocom.srvpamh.feignclient.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class YkmHandleServiceImpl implements YkmHandleService {

	private final Logger logger = LoggerFactory.getLogger(YkmHandleServiceImpl.class);

	@Autowired
	private AccessClientService accessClientService;

	@Autowired
	private WebSocketApiClientService webSocketApiClientService;

	@Autowired
	private MjRecodeFeignService mjRecodeFeignService;

	@Resource
	private RedisUtil redisUtil;

	@Autowired
	private MqSimpleFeign mqSimpleFeign;

	@Autowired
	private CompanyClientService companyClientService;

	@Autowired
	private PayConfigClientService payConfigClientService;

	@Autowired
	private HumanClientService humanClientService;

//	@Autowired
//	private SrvpaccessClientService srvpaccessClientService;

	@Override
	public boolean HandleYct(DoorRecodeVo doorRecodeVo) {

		try {
			//异常  超时  数据错误等处理
			if (!doorRecodeVo.getCheckStatus().equals("200")) {
				recode(doorRecodeVo);
				return true;
			}

			//门禁记录操作
			boolean bo = recode(doorRecodeVo);
			if (!bo) {
				return false;
			}

			//websocket
			try {
				doorRecodeVo.setPName(StringUtils.desValue(doorRecodeVo.getPName(), 1, 1, "*"));
				doorRecodeVo.setPCode(StringUtils.desValue(doorRecodeVo.getPCode(), 4, 4, "*"));
				doorRecodeVo.setPPhone(StringUtils.desValue(doorRecodeVo.getPPhone(), 4, 4, "*"));
				webSocketApiClientService.webSocketMsg(doorRecodeVo);
			} catch (Exception e) {
				logger.info("防疫接口#大屏展示推送异常:请求参数:【{}】,返回参数:【{}】", doorRecodeVo, e);
			}

		} catch (Exception e) {
			logger.info("【防疫接口记录上传/大屏/人员匹配】记录上传和大屏：【{}】", e);
		}
		return true;

	}

	public boolean recode(DoorRecodeVo doorRecodeVo) {
		//保存记录
		Result<RegionAreaInfo> resultAccess = null;
		Gson gson = new Gson();
		try {

			if (doorRecodeVo.getCheckStatus().equals("200")) {
				resultAccess = accessClientService.getAreaInfoByMachNo(doorRecodeVo.getComId().longValue(), doorRecodeVo.getDeviceNo());
				if (resultAccess.getCode() == 200) {
					doorRecodeVo.setAreaId(resultAccess.getData().getAreaId());
					doorRecodeVo.setAreaName(resultAccess.getData().getAreaName());
					doorRecodeVo.setRegionId(resultAccess.getData().getRegionId());
					doorRecodeVo.setRegionName(resultAccess.getData().getRegionName());
				}
			}
			Result result = mjRecodeFeignService.saveAccessRecord(doorRecodeVo);
			if (result.getCode() != 200) {
				logger.info("羊城通信息#门禁记录上传异常:请求参数:【{}】,返回参数:【{}】", doorRecodeVo, result);
			}
		} catch (Exception e) {
			logger.info("羊城通信息#门禁记录上传:请求参数:【{}】,返回参数:【{}】", doorRecodeVo, e.getMessage());
			return false;
		}


		//判断区域
		if(doorRecodeVo.getAreaId()==null || doorRecodeVo.getAreaId()==0 || doorRecodeVo.getPId()== 0 && !doorRecodeVo.getCheckStatus().equals("200")){
			return true;
		}

		try {
			if(resultAccess!=null){
				//进
				UpdateUserRegionRequest updateUserRegionRequest=new UpdateUserRegionRequest();
				updateUserRegionRequest.setRegionId(doorRecodeVo.getAreaId());
				updateUserRegionRequest.setComId(doorRecodeVo.getComId().longValue());
				updateUserRegionRequest.setPId(doorRecodeVo.getPId());
				Date date2=DateUtils.strToDate(doorRecodeVo.getOpenTime());
				updateUserRegionRequest.setRegionOrigId(date2.getTime()/1000);
				if(( resultAccess.getData().getIndoorState()>0 && doorRecodeVo.getOpenType()==0 )){
					updateUserRegionRequest.setRegionOnline(resultAccess.getData().getIndoorState());
					humanClientService.updateUserRegion(updateUserRegionRequest);
				}
				//出
				if(( resultAccess.getData().getOutdoorState()>0 && doorRecodeVo.getOpenType()==1 )){
					updateUserRegionRequest.setRegionOnline(resultAccess.getData().getOutdoorState());
					humanClientService.updateUserRegion(updateUserRegionRequest);
				}
			}
		}catch (Exception e){
//			logger.info( e.toString());
		}

		// 判断手机号是否为11位
		if (CommonUtil.isNull(doorRecodeVo.getPPhone()) || doorRecodeVo.getPPhone().length() != 11) {
			return true;
		}

		try {
			Long pId = doorRecodeVo.getPId().longValue();
			Long comId = doorRecodeVo.getComId().longValue();
			Integer areaId = doorRecodeVo.getAreaId();
			Long time = 7*86400l;

			//单位是否开启门禁短信功能
			boolean sendSms = false;

			// 8、从redis查找 key等于 “access_send/sms”+comId+”area”+areaID的记录;
			String canKeyWait = "company_config#comId:" + comId + "#areaId:" + doorRecodeVo.getAreaId();
			Object o = redisUtil.get(canKeyWait + areaId);
			List<EntityCompanyConfig> entityCompanyConfigs = null;
			if (o == null) {
				Result mjSMS = companyClientService.getCompanyConfig(comId, "mjSMS");
				if (mjSMS.getCode() == 200) {
					entityCompanyConfigs = JSON.parseArray(JSON.toJSONString(mjSMS.getData()),
							EntityCompanyConfig.class);
					String config = entityCompanyConfigs.get(0).getConfig();
					String[] configs = config.split(",");
					List<String> list = Arrays.asList(configs);
					if (list.contains(doorRecodeVo.getAreaId().toString())) {
						// 更新缓存
						redisUtil.set(canKeyWait, "true", time);
						sendSms = true;
					} else {
						// 保存7天
						redisUtil.set(canKeyWait, "false", time);
					}
				} else {
					// 保存7天
					redisUtil.set(canKeyWait, "false", time);
				}
			} else {
				if (o.toString().equals("true")) {
					sendSms = true;
				}
			}

			//是否可以发短信通知
			boolean canSendMes = false;

			//确认需要发短信
			if (sendSms) {

				// 9、从redis查找 key等于 “access_send/sms”+comId+”P”+pId的记录
				String canKeyUser = "accessSendSms#comId:" + comId + "#pId:" + pId;

				Object o1 = redisUtil.get(canKeyUser);
				if (o1 == null) {
					// 如果没有，调用 3.0微服务-单位 3.22获取单位功能配置列表(getCompanyConfig) ； tab='mjSMS'；如果config 存在 areaID，更新缓存执行步骤
					// 调用 3.0微服务-消费配置 13.31查询已购短信套餐（getPackagePayBySms）；有购买则保存到redis并发生短信；
					Result packagePayBySms = payConfigClientService.getPackagePayBySms(comId, pId);
					List<EntityVoucherData> entityVoucherData = JSON.parseArray(JSON.toJSONString(packagePayBySms.getData()),
							EntityVoucherData.class);
					if (!entityVoucherData.isEmpty()) {
						String endDateStr = DateUtils.getDate();
						Date endDate = DateUtils.strToDate2(endDateStr);
						for (EntityVoucherData entityVoucherData1 : entityVoucherData) {
							if (entityVoucherData1.getStopDate().compareTo(endDate) > 0) {
								endDate = entityVoucherData1.getStopDate();
							}
						}
						//优惠券截止时间
						long stopTimestamp = endDate.getTime() + 86400000l;
						//截止到现在有效期
						long canSendSecond = (stopTimestamp - System.currentTimeMillis()) / 1000;
						redisUtil.set(canKeyUser, 1, canSendSecond);
						canSendMes = true;
					} else {
						redisUtil.set(canKeyUser, 0, time);
					}
				} else {
					//可以发短信
					if ((Integer) o1 == 1) {
						canSendMes = true;
					}
				}
			}

			if(canSendMes){
				this.sms(doorRecodeVo);
			}



		} catch (Exception e) {
			logger.info("发送短信失败:请求参数:【{}】,返回参数:【{}】", doorRecodeVo, e.getMessage());
		}

		return true;
	}

	public void sms(DoorRecodeVo doorRecodeVo) {

		if(!redisUtil.lock("mjSmsLock:"+doorRecodeVo.getDeviceNo()+"#recordId"+doorRecodeVo.getRecodeId(),600)){
			return;
		}

		String pPhone = doorRecodeVo.getPPhone();
		Long comId = doorRecodeVo.getComId().longValue();
		// 判断手机号是否为11位

		// 根据companyId查询机构信息
		Result companyInfo = companyClientService.getCompanyInfoById(comId);
		EntityCompanyInfo entityCompanyInfo = JSON.parseObject(JSON.toJSONString(companyInfo.getData()),
				EntityCompanyInfo.class);

		SmsRequest smsRequest = new SmsRequest();
		smsRequest.setSecretId("AKIDcLzhN0a8e8eChEnaQG8zpifcabfnu5JX");
		smsRequest.setSecretKey("Kh6VozznPn13ECwSlphN9jCVaRLTPIPa");
		smsRequest.setSignName("鑫澳康科技");
		smsRequest.setSdkAppId("1400314290");
		smsRequest.setTemplateId("2188627");
		smsRequest.setPhone(pPhone);
		smsRequest.getParams().add(entityCompanyInfo.getComName());
		smsRequest.getParams().add(doorRecodeVo.getPName());
		smsRequest.getParams().add(doorRecodeVo.getOpenTime());
		smsRequest.getParams().add(doorRecodeVo.getAreaName());
		//开门类型。（0 未知 ，1：进入  2：离开）
		String openType  = doorRecodeVo.getOpenType()==0 ? "进入" :
				doorRecodeVo.getOpenType()==1 ? "离开" : "未知";
		smsRequest.getParams().add(openType);

		mqSimpleFeign.FySms(smsRequest);
	}

}
